<?php

namespace frontend\controllers;
use yii;
use yii\db\Query;
use common\models\Region;
use common\models\Address;
use common\models\PasswordForm;
use common\models\User;
use common\models\Product;
use yii\data\Pagination;
use common\models\LoginForm;
use common\models\SmsWeb;
use common\components\Myhelpers;
class AccountController extends FController
{
    public $enableCsrfValidation = false;
    public $layout = 'left.php';

    public function init(){
        parent::init();
        if(Yii::$app->user->isGuest){
            $this->redirect('/site/login');
            Yii::$app->end();
        }
    }

    //设置银行卡 
    public function actionIndex()
    {
        return $this->render('Index');
    }

	//退换货列表
    public function actionReturn()
    {
        return $this->render('return');
    }

    public function actionReturnlist()
    {
        return $this->render('returnlist');
    }

    public function actionReturndetail()
    {
        return $this->render('returndetail');
    }

    //退换货申请提交页
    public function actionReturnsubmit()
    {
    	return $this->render('returnsubmit');
    }


    //确认订单
    public function actionConfirm_order()
    {
    	return $this->render('confirm_order');
    }

    //已购商品的评价
    public function actionGoodsreviews()
    {
    	return $this->render('goodsreviews');
    }

    //我的收藏--商品
    public function actionCollect()
    {
        //根据登陆id查询对应的收藏记录及商品详情
        $uid = Yii::$app->user->id;
        $where = "a.user_id = ".$uid;

        //筛选收藏
        $goodsname = Myhelpers::RemoveXSS(Yii::$app->request->get('goodsname'));
        if($goodsname){
            $where .= " and b.name like '%".$goodsname."%'";
        }

        $collect = (new \yii\db\Query())
                ->select('a.id cid,b.*')
                ->from('collection a')
                ->where($where)
                ->leftJoin(['b'=>'product'],'b.id = a.product_id')
                ->groupBy('b.id')
                /*->all()*/;

        //框架自带的跳转分页
        $pages = new Pagination(
            [
                'totalCount' => $collect->count(),
                /*'pageSize'=>'3',*/
                'defaultPageSize' => 6,        //------自行设置每页显示的资金明细记录
                'validatePage' => false,
            ]
        );

        $list = $collect->limit($pages->limit)->offset($pages->offset)->all();

        //根据传过来的id取消收藏
        $pid = Yii::$app->request->post('pid');
        if($pid){
            if(is_array($pid)){
                $res = 0;
                foreach ($pid as $key => $value) {
                    $res += Yii::$app->db->createCommand()
                         ->Delete('collection', ['product_id'=>$value,'user_id'=>$uid])
                         ->execute();
                }
                $res = $res<count($pid)?0:1;
            }else{
                $res = Yii::$app->db->createCommand()
                     ->Delete('collection', ['id'=>$pid])
                     ->execute();
            }
            return $res;
        }

    	return $this->render('collect',[
            'list' => $list,
            'pages' => $pages,
        ]);
    }

	//收货地址
    public function actionShipaddress()
    {
        //查询当前用户默认的收货地址
        $address = Address::find()
                ->select('*')
                ->where(['is_show' => 1,'user_id'=>Yii::$app->user->id])
                ->asArray()
                ->all();

        foreach ($address as $key => $value) {
            $address[$key]['province1'] = Region::region_list($value['province']);
            $address[$key]['city1'] = Region::region_list($value['city']);
            $address[$key]['district1'] = Region::region_list($value['district']);
            $address[$key]['phone1'] = substr_replace($value['phone'],'****',3,4);
        }
        //配送地区三级联动
        $province = Region::find()
                ->select('id,name')
                ->where(['level'=>1])
                ->asArray()
                ->orderBy("id")
                ->all();
        //var_dump($province);

        //用传过来的省的ID查询下级城市---默认查询一个三级区域
        $province_id = Yii::$app->request->post('province_id');

        if($province_id){
            $city = Region::find()
                    ->select('id,name')
                    ->where(['level'=>2,'parent_id'=>$province_id])
                    ->asArray()
                    ->all();
            $city[0]['list'] = Region::find()
                    ->select('id,name')
                    ->where(['level'=>3,'parent_id'=>$city[0]['id']])
                    ->asArray()
                    ->all();
            return json_encode($city);
        }

        //用传过来的市的ID查询下级地区
        $city_id = Yii::$app->request->post('city_id');

        if($city_id){
            $town = Region::find()
                    ->select('id,name')
                    ->where(['level'=>3,'parent_id'=>$city_id])
                    ->asArray()
                    ->all();
            return json_encode($town);
        }

        $addr_id = Yii::$app->request->post('addr_id');

        if(!is_null($addr_id)){
            return json_encode($address[$addr_id]);
        }

        //删除数据
        $add_del_id = Yii::$app->request->post('add_del_id');
        if($add_del_id){

            $del = Address::findOne($add_del_id)->delete();
            
            return $del_res = $del?$del:0;
        }

        //增加数据
        $add_save_data = Yii::$app->request->post('save_update');
        $post_data = json_decode($add_save_data,true);

        if( $post_data ){
            if(!$post_data[1] || !$post_data[2] || strlen($post_data[2])!=11 || !$post_data[5] || !$post_data[6] || !$post_data[7] || !$post_data[8]){
                return 0;
            }
        }
        if($post_data[1]){
            $data['user_id'] = Yii::$app->user->id;
            $data['name'] = $post_data[1];
            $data['province'] = $post_data[6];
            $data['city'] = $post_data[7];
            $data['district'] = $post_data[8];
            $data['address_detail'] = $post_data[5];
            $data['phone'] = $post_data[2];
            $data['tel'] = $post_data[3];
            $data['zip_code'] = $post_data[4];

            if($post_data[0] == ""){
                $save_res = Yii::$app->db->createCommand()
                ->insert('address',$data)
                ->execute();
            }else{
                $save_res = Yii::$app->db->createCommand()
                ->update('address', $data, 
                    'id = '.$address[$post_data[0]]['id'])
                ->execute();
            }
            
            return $save_res = $save_res?$save_res:0;
        }
        //修改页面标题
        Yii::$app->view->params['page']['page_title'] = '管理收货地址 - ' . $this->w_config['website_name'];
    	return $this->render('shipaddress',[
            'province' => $province,
            'address' => $address,
        ]);
    }

    //重置密码
    public function actionResetpassword()
    {
       $model=new PasswordForm;
       $m = new LoginForm;
        $request = YII::$app->request;
        $error = 0;
        if($request->isPost){
            $p = $request->post('PasswordForm');
            $id = YII::$app->user->id;
            $admin=  User::findIdentity($id);
            $password = $admin->password_hash;
            if(Yii::$app->getSecurity()->validatePassword($p['password_hash'], $password)){
                if($p['pass1'] == $p['pass2']){
                    $newPass = Yii::$app->getSecurity()->generatePasswordHash($p['pass1']);
                    $connection = \Yii::$app->db;
                    $r = $connection->createCommand()->update('user', ['password_hash' => $newPass], 'id='.$id)->execute();
                    if($r){
                         //发站内信
                     $web_arr = array(
                        'id' => $id,
                        'type' => 1,
                     );
                     $web_result = SmsWeb::sendWeb($web_arr);
                        Yii::$app->user->logout();
                        return $this->redirect('/site/login');
                    }else{
                        return $this->goBack();
                    }
                }else{
                    $error = 1;
                    Yii::$app->session->setFlash('contact','密码输入不一致');
                   return $this->render('resetpassword',['model'=>$model,'error'=>$error,'m'=>$m]);
                }
            }else{
                $error = 2;
                Yii::$app->session->setFlash('contact','旧密码错误');
                return $this->render('resetpassword',['model'=>$model,'error'=>$error,'m'=>$m]);
            }
        }else{
            return $this->render('resetpassword',['model'=>$model,'error'=>$error,'m'=>$m]);
        }
    	
    }
    
    //商品搜索结果
    public function actionSearch_results()
    {
    	return $this->render('search_results');
    }

}
